import { openDB } from 'idb'
import type { DBSchema, IDBPDatabase } from 'idb'

// 任务列表数据接口
export interface TaskListData {
  id: string
  title: string
  description: string
  subject: string
  studentCount: number
  startTime: string
  endTime: string
  status: string
  statusList: Array<{
    type: string
    label: string
    completed: boolean
  }>
  teacherID: string // 添加教师ID
  createdAt: string
  updatedAt: string
}

// IndexedDB数据库结构
interface TaskListDB extends DBSchema {
  tasklist: {
    key: string
    value: TaskListData
    indexes: {
      'by-subject': string
      'by-status': string
      'by-created': string
    }
  }
}

class TaskListStorage {
  private db: Promise<IDBPDatabase<TaskListDB>>

  constructor() {
    this.db = openDB<TaskListDB>('homework-grading-system', 1, {
      upgrade(db) {
        // 创建tasklist对象存储
        const taskStore = db.createObjectStore('tasklist', { keyPath: 'id' })

        // 创建索引
        taskStore.createIndex('by-subject', 'subject')
        taskStore.createIndex('by-status', 'status')
        taskStore.createIndex('by-created', 'createdAt')
      },
    })
  }

  // 初始化数据库
  async init(): Promise<void> {
    await this.db

    // 检查是否需要初始化示例数据
    const existingTasks = await this.getTasks()
    if (existingTasks.length === 0) {
      await this.initSampleData()
    }
  }

  // 初始化示例数据
  private async initSampleData(): Promise<void> {
    // 动态导入翻译函数
    const { t } = await import('@/plugins/i18nPlugin')

    const sampleTasks: TaskListData[] = [
      {
        id: 'task-001',
        title: t('assets.sampleData.mathTask'),
        description: t('assets.sampleData.mathTaskDesc'),
        subject: 'math',
        studentCount: 25,
        startTime: '2024-01-15 09:00:00',
        endTime: '2024-01-20 18:00:00',
        status: 'pending',
        statusList: [
          { type: 'created', label: t('assets.taskList.created'), completed: true },
          { type: 'pending', label: t('assets.taskList.pending'), completed: false },
          { type: 'correction', label: t('assets.taskList.correction'), completed: false }
        ],
        teacherID: 'teacher-001',
        createdAt: '2024-01-15 08:00:00',
        updatedAt: '2024-01-15 08:00:00'
      },
      {
        id: 'task-002',
        title: t('assets.sampleData.chineseTask'),
        description: t('assets.sampleData.chineseTaskDesc'),
        subject: 'chinese',
        studentCount: 28,
        startTime: '2024-01-16 10:00:00',
        endTime: '2024-01-22 17:00:00',
        status: 'grading',
        statusList: [
          { type: 'created', label: t('assets.taskList.created'), completed: true },
          { type: 'pending', label: t('assets.taskList.pending'), completed: true },
          { type: 'correction', label: t('assets.taskList.correction'), completed: false }
        ],
        teacherID: 'teacher-001',
        createdAt: '2024-01-16 09:00:00',
        updatedAt: '2024-01-18 14:30:00'
      },
      {
        id: 'task-003',
        title: t('assets.sampleData.englishTask'),
        description: t('assets.sampleData.englishTaskDesc'),
        subject: 'english',
        studentCount: 30,
        startTime: '2024-01-17 14:00:00',
        endTime: '2024-01-24 16:00:00',
        status: 'completed',
        statusList: [
          { type: 'created', label: t('assets.taskList.created'), completed: true },
          { type: 'pending', label: t('assets.taskList.pending'), completed: true },
          { type: 'correction', label: t('assets.taskList.correction'), completed: true }
        ],
        teacherID: 'teacher-001',
        createdAt: '2024-01-17 13:00:00',
        updatedAt: '2024-01-20 16:45:00'
      }
    ]

    for (const task of sampleTasks) {
      await this.saveTask(task)
    }
  }

  // 获取所有任务
  async getTasks(): Promise<TaskListData[]> {
    const db = await this.db
    return db.getAll('tasklist')
  }

  // 根据ID获取任务
  async getTaskById(id: string): Promise<TaskListData | undefined> {
    const db = await this.db
    return db.get('tasklist', id)
  }

  // 根据状态获取任务
  async getTasksByStatus(status: string): Promise<TaskListData[]> {
    const db = await this.db
    const allTasks = await db.getAll('tasklist')

    if (status === 'all') {
      return allTasks
    }

    // 根据状态筛选
    return allTasks.filter(task => {
      switch (status) {
        case 'pending':
          return ['pending', 'grading'].includes(task.status)
        case 'correction':
          return ['correction', 'correcting'].includes(task.status)
        case 'completed':
          return task.status === 'completed'
        default:
          return task.status === status
      }
    })
  }

  // 根据学科获取任务
  async getTasksBySubject(subject: string): Promise<TaskListData[]> {
    const db = await this.db
    return db.getAllFromIndex('tasklist', 'by-subject', subject)
  }

  // 保存任务
  async saveTask(task: TaskListData): Promise<string> {
    const db = await this.db
    task.updatedAt = new Date().toISOString().replace('T', ' ').substring(0, 19)
    await db.put('tasklist', task)
    return task.id
  }

  // 删除任务
  async deleteTask(id: string): Promise<void> {
    const db = await this.db
    await db.delete('tasklist', id)
  }

  // 清空所有任务
  async clearTasks(): Promise<void> {
    const db = await this.db
    await db.clear('tasklist')
  }

  // 强制重新初始化示例数据（用于语言切换后更新数据）
  async forceReinitSampleData(): Promise<void> {
    await this.clearTasks()
    await this.initSampleData()
  }

  // 搜索任务
  async searchTasks(keyword: string): Promise<TaskListData[]> {
    const db = await this.db
    const allTasks = await db.getAll('tasklist')

    if (!keyword.trim()) {
      return allTasks
    }

    const lowerKeyword = keyword.toLowerCase()
    return allTasks.filter(task =>
      task.title.toLowerCase().includes(lowerKeyword) ||
      task.description.toLowerCase().includes(lowerKeyword) ||
      task.subject.toLowerCase().includes(lowerKeyword)
    )
  }

  // 更新任务状态
  async updateTaskStatus(id: string, status: string): Promise<void> {
    const task = await this.getTaskById(id)
    if (task) {
      task.status = status
      task.updatedAt = new Date().toISOString().replace('T', ' ').substring(0, 19)

      // 更新状态列表
      task.statusList.forEach(statusItem => {
        if (statusItem.type === status) {
          statusItem.completed = true
        }
      })

      await this.saveTask(task)
    }
  }
}

// 导出单例实例
export const taskListStorage = new TaskListStorage()